import React from 'react'
import { createRoot } from 'react-dom/client'
import './styles/base.css'
import './styles/index.css'

import TodoHeader from './components/TodoHeader'
import TodoMain from './components/TodoMain'
import TodoFooter from './components/TodoFooter'
class App extends React.Component {
  state = {
    list: [
      { id: 1, name: '吃饭', done: false },
      { id: 2, name: '睡觉', done: false },
      { id: 3, name: '打豆豆', done: true },
    ],
  }
  handleAdd = (newItem) => {
    let id
    if (this.state.list.length === 0) {
      id = 1
    } else {
      id = this.state.list[this.state.list.length - 1].id + 1
    }
    this.setState({
      list: [...this.state.list, { id, name: newItem, done: false }],
    })
  }
  handleRemove = (id) => {
    this.setState({
      list: this.state.list.filter((item) => item.id !== id),
    })
  }
  handleChangeDone = (id) => {
    const list = [...this.state.list]
    const index = list.findIndex((item) => item.id === id)
    list[index].done = !list[index].done
    this.setState({
      list,
    })
  }
  handleToggleAll = (done) => {
    console.log(done)
    const list = [...this.state.list]
    list.forEach((item) => (item.done = done))
    this.setState({
      list,
    })
  }
  render() {
    return (
      <section className="todoapp">
        <TodoHeader add={this.handleAdd}></TodoHeader>
        <TodoMain
          list={this.state.list}
          remove={this.handleRemove}
          changeDone={this.handleChangeDone}
          toggleAll={this.handleToggleAll}
        ></TodoMain>
        <TodoFooter></TodoFooter>
      </section>
    )
  }
}

const root = createRoot(document.getElementById('root'))

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
)
